cmake_minimum_required(VERSION 3.22)

# Setup compiler settings
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS ON)
set(CMAKE_C_COMPILER_ID "GNU")
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -x c")

# Define the build type
if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE "Debug")
endif()

# Set the project name
set(CMAKE_PROJECT_NAME um321xf-cmake)

# Include toolchain file
include("cmake/gcc-arm-none-eabi.cmake")

# Enable compile command to ease indexing with e.g. clangd
set(CMAKE_EXPORT_COMPILE_COMMANDS TRUE)

# Core project settings
project(${CMAKE_PROJECT_NAME})

# Enable CMake support for ASM and C languages
enable_language(C ASM)
message("Build type: " ${CMAKE_BUILD_TYPE})


# Create an executable object type
add_executable(${CMAKE_PROJECT_NAME}
        Soft_Driver/Inc/app_adc.h
        Soft_Driver/Src/app_adc.c)

#add_library(${CMAKE_PROJECT_NAME})
add_subdirectory(cmake/um321xf)

# Link directories setup
target_link_directories(${CMAKE_PROJECT_NAME} PRIVATE
        # Add user defined library search paths
)

# Add sources to executable
target_sources(${CMAKE_PROJECT_NAME} PRIVATE
        ./Core/Src/main.c
        ./Soft_Driver/Src/systick.c
        ./Soft_Driver/Src/app_uart.c
        ./Soft_Driver/Src/app_gpio.c
        ./Soft_Driver/Src/app_adc.c
)

# Add include paths
target_include_directories(${CMAKE_PROJECT_NAME} PRIVATE
        # Add user defined include paths
        ./Core/Inc
        ./Soft_Driver/Inc
)

# Add project symbols (macros)
target_compile_definitions(${CMAKE_PROJECT_NAME} PRIVATE
        # Add user defined symbols
)

# Add linked libraries
target_link_libraries(${CMAKE_PROJECT_NAME}
        um321xf
        # Add user defined libraries
)

# 设置输出路径
set_target_properties(${CMAKE_PROJECT_NAME} PROPERTIES
        LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/build
        ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/build
        RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/build
)

set_source_files_properties(um321xf PROPERTIES
        OBJECT_OUTPUTS "${CMAKE_CURRENT_BINARY_DIR}/build/${CMAKE_PROJECT_NAME}.o"
        COMPILE_FLAGS "-o ${CMAKE_CURRENT_BINARY_DIR}/build/${CMAKE_PROJECT_NAME}.o --omf_browse ${CMAKE_CURRENT_BINARY_DIR}/build/${CMAKE_PROJECT_NAME}.crf --depend ${CMAKE_CURRENT_BINARY_DIR}/build/${CMAKE_PROJECT_NAME}.d"
)

set(HEX_FILE ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.hex)
set(BIN_FILE ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.bin)

# 添加生成.bin文件的目标
add_custom_command(
        TARGET ${PROJECT_NAME}
        POST_BUILD
        COMMAND ${CMAKE_OBJCOPY} -O binary $<TARGET_FILE:${PROJECT_NAME}> ${BIN_FILE}
        COMMENT "Building ${BIN_FILE}"
)

# 添加生成.hex文件的目标
add_custom_command(
        TARGET ${PROJECT_NAME}
        POST_BUILD
        COMMAND ${CMAKE_OBJCOPY} -O ihex $<TARGET_FILE:${PROJECT_NAME}> ${HEX_FILE}
        COMMENT "Building ${HEX_FILE}"
)